import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { environment } from '../../../../../../../src/environments/environment';
import { SearchComponent } from '../../modal/search/search.component'
import { EditComponent } from '../../modal/edit/edit.component'
import { FlowInfoComponent } from '../../modal/flow-info/flow-info.component';
import { HistoryChangeComponent } from '../../modal/history-change/history-change.component';
import { ReadingNotesComponent } from '../../modal/reading-notes/reading-notes.component';
import { ViewPageService } from '../view-page/view-page.service';
import { DataService } from '../../../../../services/data.service'
import { EntryChangeComponent } from '../../modal/entry-change/entry-change.component';
import * as _ from "lodash";
import { TablePageComponent } from '../../modal/table/table-page/table-page.component';

@Component({
  selector: 'app-view-page',
  templateUrl: './view-page.component.html',
  styleUrls: ['./view-page.component.scss'],
  providers: [ViewPageService]
})
export class ViewPageComponent implements OnInit {

  // 条目查看列表
  @ViewChild("qdiiViewTablePage", { read: ViewContainerRef })
  qdiiViewTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  //搜索#search modal1
  @ViewChild("search", { read: ViewContainerRef })
  search: ViewContainerRef;
  searchComponent: ComponentRef<SearchComponent>;

  public cloneList:any = [];
  //查看#edit modal2
  @ViewChild("edit", { read: ViewContainerRef })
  edit: ViewContainerRef;
  editComponent: ComponentRef<EditComponent>;

  //查看流程信息#flowInfo modal3
  @ViewChild("flowInfo", { read: ViewContainerRef })
  flowInfo: ViewContainerRef;
  flowInfoComponent: ComponentRef<FlowInfoComponent>;

  //查询历史变更数据#historyChange modal6
  @ViewChild("historyChange", { read: ViewContainerRef })
  historyChange: ViewContainerRef;
  historyChangeComponent: ComponentRef<HistoryChangeComponent>;

  // 阅读维护须知正文#readingNotes modal7
  @ViewChild("readingNotes", { read: ViewContainerRef })
  readingNotes: ViewContainerRef;
  readingNotesComponent: ComponentRef<ReadingNotesComponent>;

  //条目修改
  @ViewChild("entryChange", { read: ViewContainerRef })
  entryChange: ViewContainerRef;
  entryChangeComponent: ComponentRef<EntryChangeComponent>;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  public listData: any = [];

  //查询列表getBody
  public getBody: any = {
    pageIndex: 1,
    pageSize: 50,
    nQdIdList: '',
    sValid: '',
    sFileSource: '',
  };

  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //列表全选
  public isCheckedAll: any = false;

  constructor(
    public resolver: ComponentFactoryResolver,
    public viewService: ViewPageService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    let that = this;
    this.loadlist();
    this.dataService.QDIIReadInfoEmitter = new EventEmitter();
    this.dataService.QDIIReadInfoEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'searchBody':
            that.getBody = _.cloneDeep(that.dataService.searchBody);
            console.log(that.dataService.searchBody)
            console.log(that.getBody)
            this.loadlist();
            window['$']('#search').modal('hide');
            break;
        }
      }
    })
    this.dataService.QDIIsEntryChangeEmitter = new EventEmitter();
    this.dataService.QDIIsEntryChangeEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'entryChangeSave':
            window['$']('#entryChange').modal('hide');
            that.loadlist();
            break;
          case 'refreshViewList':
            window['$']('#entryChange').modal('hide');
            that.loadlist();
            break;
        }
      }
    })
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == 'QDII条目管理') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '查看QDII条目') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-QDII', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == 'QDII条目管理') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '查看QDII条目') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-QDII', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    console.info(this.menuResourceSet)
  }

  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }

  loadlist(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    // 查询条件转码
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.viewService.list(this.getBody).subscribe(data => {
      if (data) {
        console.log(data);
        this.listData = data.list;
        this.cloneList = _.cloneDeep(data.list)
        this.showTablePage(this.listData);
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
      }
    })
  }

  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }

  // 导出
  exportExcel() {
    let that = this;
    let nQdIdList: any = [];

    // console.log("===============");
    // let checkedItem = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        nQdIdList.push(item.nQdId);
      }
    })
    // nQdIdList=checkedItem;
    // let converItem: any = checkedItem.join(',');
    // let getBody = {
    //   "nAuditNoList": converItem,
    //   "sFundType": this.annuityCheckBody.sFundType,
    //   "sFullName": this.annuityCheckBody.sFullName,
    //   "sFundCode": this.annuityCheckBody.sFundCode,
    //   "sModifyItem": this.annuityCheckBody.sModifyItem
    // }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    // getBody.sFullName = encodeURI(getBody.sFullName)
    iframe.attr('src', environment.server + '/pms/v1/riskmanage/qdiiData/export/exportQdiiData?token=' + sessionStorage.getItem('token') + '&nQdIdList=' + nQdIdList);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }


  //显示搜索#search modal1
  showSearchModal() {
    this.showSearch();
    window['$']('#search').modal('show');
  }

  //显示查看#edit modal2
  showEditModal() {
    let that = this;
    // switch (type) {
    //   case "dbclick":
    //     this.showEdit(item);
    //     window['$']('#modal2').modal('show');
    //     break;
    //   case "one":
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行查看!", "warning")
    }
    else if (checkProduct.length == 1) {
      this.showEdit(checkProduct[0]);
      console.log(checkProduct[0]);
      window['$']('#edit').modal('show');
    }
    else {
      window['swal']("注意", "只能选择一条记录进行查看!", "warning")
    }
    //     break;
    // }
  }

  //显示流程信息#flowInfo modal3
  showFlowInfoModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行查看!", "warning")
    }
    else if (checkProduct.length == 1) {
      this.showFlowInfo(checkProduct[0]);
      console.log(checkProduct[0]);
      window['$']('#flowInfo').modal('show');
    }
    else {
      window['swal']("注意", "只能选择一条记录进行查看!", "warning")
    }
  }
  //判断选中的条目数量
  entryCount() {
    let entryList: any = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        delete item.isChecked;
        entryList.push(item);
      }
    })
    return entryList;
  }
  // 条目修改
  showEntryChange() {
    let count: any = this.entryCount();
    let onPassageList: any = [];
    let unOnPassageItem: any;
    if (count.length != 0) {
      // 判断组件是否已创建，如果创建先注销
      if (this.entryChangeComponent && this.entryChangeComponent.instance) {
        this.entryChangeComponent.destroy();
      }
      _.forEach(count, item => {
        delete item.isChecked;
        if (item.sState != '正常') {
          onPassageList.push(item.nQdId)
        }
      })
      unOnPassageItem = onPassageList.join(',')
      // 动态创建组件的实例
      if (onPassageList.length > 0) {
        window['swal']("提示", "仅能修改正常状态的数据", "warning")
      } else {
        const entryChangeComponent = this.resolver.resolveComponentFactory(EntryChangeComponent);
        this.entryChangeComponent = this.entryChange.createComponent(entryChangeComponent);
        this.entryChangeComponent.instance.list = count;
        console.log(count);

        window['$']('#entryChange').modal('show');
      }

    } else {
      window['swal']("提示", "请选择数据", "warning")
    }
  }
  //查询历史变更数据#historyChange modal6
  showHistoryChangeModal() {
    let that = this;
    let checkProduct = [];
    let nQdIds: any;
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item.nQdId);
      }
    })
    nQdIds = checkProduct.join(',');
    // let getBody:any={
    //   pageIndex:1,
    //   pageSize:10,
    //   nQdId:checkProduct,
    //   sOprDateStart:'',
    //   sOprDateEnd:''
    // }
    // this.viewService.listChange(this.getBody).subscribe(data => {
    //   if (data) {
    //     console.log(data);
    //     this.listData = data.list;
    //     this.listPageInfo.currentPageNum = data.pageNum;
    //     this.listPageInfo.totalPages = data.pages;
    //     this.listPageInfo.total = data.total;
    //     this.listPageInfo.startRow = data.startRow;
    //     this.listPageInfo.endRow = data.endRow;
    //   }
    // })
    this.showHistoryChange(nQdIds);
    console.log(typeof checkProduct);
    window['$']('#historyChange').modal('show');

  }

  //搜索#search modal1创建 
  showSearch() {
    // 判断组件是否已创建，如果创建先注销
    if (this.searchComponent && this.searchComponent.instance) {
      this.searchComponent.destroy();
    }
    // 动态创建组件的实例
    const searchComponent = this.resolver.resolveComponentFactory(SearchComponent);
    this.searchComponent = this.search.createComponent(searchComponent);
    // this.searchComponent.instance.getBody = this.getBody;
    // this.editComponent.instance.item = item;
    // this.editComponent.instance.nFgId = item.nFgId;
    // this.editComponent.instance.sType = item.sType;
  }

  //查看#edit modal2创建
  showEdit(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.editComponent && this.editComponent.instance) {
      this.editComponent.destroy();
    }
    // 动态创建组件的实例
    const editComponent = this.resolver.resolveComponentFactory(EditComponent);
    this.editComponent = this.edit.createComponent(editComponent);
    this.editComponent.instance.item = item;
  }

  // 查看流程信息#flowInfo modal3创建
  showFlowInfo(item) {
    if (this.flowInfoComponent && this.flowInfoComponent.instance) {
      this.flowInfoComponent.destroy();
    }
    // 动态创建组件的实例
    const flowInfoComponent = this.resolver.resolveComponentFactory(FlowInfoComponent);
    this.flowInfoComponent = this.flowInfo.createComponent(flowInfoComponent);
    this.flowInfoComponent.instance.item = item;
  }

  // 查询历史变更数据#historyChange modal6创建
  showHistoryChange(nQdIds) {
    if (this.historyChangeComponent && this.historyChangeComponent.instance) {
      this.historyChangeComponent.destroy();
    }
    // 动态创建组件的实例
    const historyChangeComponent = this.resolver.resolveComponentFactory(HistoryChangeComponent);
    this.historyChangeComponent = this.historyChange.createComponent(historyChangeComponent);
    this.historyChangeComponent.instance.nQdIds = nQdIds;
  }

  // 显示阅读维护须知#readingNotes modal7创建
  showReadingNote() {
    // 判断组件是否已创建，如果创建先注销
    if (this.readingNotesComponent && this.readingNotesComponent.instance) {
      this.readingNotesComponent.destroy();
    }
    // 动态创建组件的实例
    const readingNotesComponent = this.resolver.resolveComponentFactory(ReadingNotesComponent);
    this.readingNotesComponent = this.readingNotes.createComponent(readingNotesComponent);
    // window['$']('#modal7').modal('show');
  }

  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.listData, [colName], ["asc"]);
    if (JSON.stringify(this.listData) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.listData, [colName], ["desc"]);
    }
    this.listData = listDataAsc;
  }
  // 条目查看列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.qdiiViewTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '1';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
